import * as vscode from 'vscode';
import { v4 as uuidv4 } from 'uuid';
import { ProxyService } from './proxyService';

/**
 * Defines the structure for an analytics event payload.
 */
export interface AnalyticsEvent {
    eventId: string;          // Unique ID for the event
    eventName: string;        // Name of the event, e.g., 'optimizeCode.invoked'
    timestamp: string;        // ISO 8601 timestamp of when the event occurred
    vscodeVersion: string;    // Version of the user's VS Code instance
}

/**
 * A singleton service to handle the collection and dispatching of analytics events.
 * It provides a unified, "fire-and-forget" interface for all feature modules.
 */
export class AnalyticsService {
    private static instance: AnalyticsService;
    private proxyService: ProxyService;

    private constructor(context: vscode.ExtensionContext) {
        this.proxyService = ProxyService.getInstance(context);
    }

    /**
     * Retrieves the singleton instance of the AnalyticsService.
     */
    public static getInstance(context: vscode.ExtensionContext): AnalyticsService {
        if (!AnalyticsService.instance) {
            AnalyticsService.instance = new AnalyticsService(context);
        }
        return AnalyticsService.instance;
    }

    /**
     * Tracks a specific event. This is the main entry point for other modules.
     * @param eventName A descriptive name for the event.
     * @param props A dictionary of custom properties to include with the event.
     */
    public trackEvent(eventName: string, props: { [key: string]: any } = {}): void {
        const now = new Date();
        const timestamp = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
        
        const eventData: AnalyticsEvent = {
            eventId: uuidv4(),
            eventName: eventName,
            timestamp: timestamp,
            vscodeVersion: vscode.version
        };

        this.sendData(eventData);
    }

    /**
     * Dispatches the event data using the ProxyService. This is a "fire-and-forget"
     * operation and does not block the caller.
     * @param data The analytics event payload.
     */
    private sendData(data: AnalyticsEvent): void {
        this.proxyService.sendAnalyticsEvent(data).catch((error: any) => {
            console.error('AnalyticsService: Failed to dispatch event via ProxyService', error);
        });
    }
} 